package kr.saeildamil.androidStudy_second.fragment.network;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;

import kr.saeildamil.androidStudy_second.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

public class Json_parserActivity extends Activity {
	ListView list;
	ProgressDialog progressDlg;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch28_xmlparser);
		list = (ListView) findViewById(R.id.listView);
		new ParsingXml().execute("order.json");
	}
	
	private class ParsingXml extends AsyncTask<String, Void, ArrayList<Item>>{
		protected void onPreExecute() {
			super.onPreExecute();
			progressDlg = ProgressDialog.show(Json_parserActivity.this, "Wait", "order.xml Parsing...");
		}
		protected void onPostExecute(ArrayList<Item> result) {
			super.onPostExecute(result);
			MyAdapter adapter = new MyAdapter(result, Json_parserActivity.this);
			progressDlg.dismiss();
			list.setAdapter(adapter);
		}

		protected ArrayList<Item> doInBackground(String... params) {
			StringBuilder sb =  new StringBuilder();
			String str="";
			try {
				BufferedReader br = new BufferedReader(new InputStreamReader(openFileInput(params[0])));
				while( (str = br.readLine()) != null ){
					sb.append(str);
				}

				br.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			return parsingXml(sb.toString());
		}
		
	}//end of class AsyncTask
	
	public ArrayList<Item> parsingXml(String json){
		ArrayList<Item> arItem = new ArrayList<Item>();
		Item itemClass;
		
		try {
			JSONArray ja = new JSONArray(json);
			
			for(int i=0; i<ja.length(); i++){
				JSONObject order = ja.getJSONObject(i);
				itemClass = new Item(order.getString("Product"), order.getString("Maker"), order.getInt("Price"));
				arItem.add(itemClass);
				
				Iterator<?> iterator = order.keys();
				while(iterator.hasNext()){
					Object obj = iterator.next();
					Log.d("aaaaa",obj.toString());
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		
		return arItem;
	}

}
